<?php
iconv_set_encoding('input_encoding','utf8');
iconv_set_encoding('output_encoding','utf8');
iconv_set_encoding('internal_encoding','utf8');
header('Content-type: text/html; charset="utf-8"',true);

class PXFInstance
{
	static $controller;
	static $action;
	static $user;
	static $lang;
	static $flashes;

	protected function __construct()
	{
		PXFRequest::parse();

		/* Check and start session required params. */
		$users = PXFModel::getModel('user'); 
		$user = (isset($_SESSION['user_id'])) ? $users->find($_SESSION['user_id']) : null;
		if(is_null($user))
		{
	  	$user = $users->find(PXFConfig::NOBODY_USER);
			$_SESSION['user_id'] = $user->id;
		}
		self::$user = $user; 

		$_SESSION['lang'] = PXFRequest::reqGet('language');
		PXFInstance::$lang    = PXFRequest::reqGet('language');
		PXFInstance::$flashes = self::getFlashMessages();
	}

	public static function getInstance()
	{
		static $instance = null;
		if(is_null($instance))
		{
			$instance = new PXFInstance();
		}
		return $instance;
	}

	public function start()	
	{
		PXFLang::init();
	}

	public function end()	
	{	
	}

	public static function breakPoint()
	{
		print '<pre>';
		$args = func_get_args();
		foreach($args as $arg)
		{
			print_r($arg);
			print "\n";
		}
		print "Session dump \n";
		print_r($_SESSION);

		print "Request dump \n";
		print_r($_REQUEST);

		print '</pre>';

		$db = PXFDataBase::getInstance();
		$db->dump();
		exit();
	}

	public static function changeUser($user)
	{
		/* Change user settings too. */
		$_SESSION['user_id'] = $user->id;
		PXFInstance::$lang 		 = $_SESSION['lang'];
		self::$user = $user; 
	}

	public static function clearSession()
	{
		/* Clear session. */
		foreach($_SESSION as $key => $value)
		{
			unset($_SESSION[$key]);
		}
	}
	
	public static function displayFlashMessage($type,$msg)
	{
		PXFInstance::$flashes[] = array('type' => $type,'msg' => $msg);
	}

	public static function pushFlashMessage($type,$msg)
	{
		/* Add flash message into session. */
		if(!isset($_SESSION['flashes']) || !is_array($_SESSION['flashes']))
		{
			$_SESSION['flashes'] = array();
		}
		$_SESSION['flashes'][] = array('type' => $type,'msg' => $msg);
	}

	private static function getFlashMessages()
	{
		/* Get flash messages and clear its on session.*/
		$msgs = (isset($_SESSION['flashes']) && is_array($_SESSION['flashes'])) ? $_SESSION['flashes'] : array();
		unset($_SESSION['flashes']);
		return $msgs;
	}

	public function response()
	{
		self::$controller = PXFRequest::getController();
		self::$action 		= PXFRequest::getAction();

		/* Load modules and execute action. */
		@include(sprintf('%s/modules/%s/controller.php',PXFConfig::PXF_SITE,self::$controller));

		$act = self::$action;
    $controller = @new Controller();
		if($controller && method_exists($controller,$act))
		{
    	$controller->$act();
		}
		else
		{
			PXFRequest::redirect404();
		}
	}

	public function userCan($controller,$action = null)
	{
		$mod_paccess = PXFModel::getModel('paccess');
		$condition   = new PXFCondition('profile_id',PXFInstance::$user->profile_id);
		$condition->add(PXFCondition::opAND('module',PXFInstance::$controller));
		if(!is_null($action))
		{
			$condition->add(PXFCondition::opAND('action',PXFInstance::$action));
		}
		return (count($mod_paccess->findBy(array('condition' => $condition))) != 0);
	}
}

class PXFRequest
{
	static $params = array();

	public static function parse()
	{
		if(defined('ROOT_ACCESS'))
		{
			PXFRequest::$params['controller'] =  PXFConfig::DEFAULT_CONTROLLER;
			PXFRequest::$params['action']     =  'index';
			return;
		}

		$websitegear = PXFConfig::REQUEST_URI;
		$query  = $_SERVER['REQUEST_URI'];
		$ini    = strpos($query,$websitegear);
		$query  = substr($query,$ini + strlen($websitegear));
		$xparams = split('\/',$query);
		
		if(!defined('PXF_ADMIN'))
		{
			PXFRequest::$params['language']   = (isset($xparams[1]) && strlen($xparams[1]) > 0) ? $xparams[1] : PXFConfig::DEFAULT_LANG;
		}
		else
		{
			PXFRequest::$params['language'] = 'es';
		}
		
		PXFRequest::$params['controller'] = (isset($xparams[2]) && strlen($xparams[2]) > 0) ? $xparams[2] : PXFConfig::DEFAULT_CONTROLLER;
		PXFRequest::$params['action']     = (isset($xparams[3]) && strlen($xparams[3]) > 0) ? $xparams[3] : 'index';

		for($x = 4; $x < count($xparams); $x+=2)
		{
			if(strlen(trim($xparams[$x])) > 0)
				PXFRequest::$params[$xparams[$x]] = $xparams[$x + 1];
		}
	} 

	public static function getController()
	{
		return PXFRequest::$params['controller'];		
	}

	public static function getAction()
	{
		return PXFRequest::$params['action'];		
	}

	public static function notNullOr404($object)
	{
		if((is_null($object)) || (!is_object($object)))
		{
			PXFRequest::redirect404();
		}
		return true;
	}

	public static function reqGet($key)
	{
		$req = null;
		if(!defined('PXF_ADMIN'))
		{
			$req = & $_POST;
		}
		else
		{
			$req = & $_REQUEST;
		}
		
		if(isset($req[$key]))
		{
			if(is_array($req[$key]) && count($req[$key]) > 0) 
			{
				return $_POST[$key];
			}
			elseif((!is_array($req[$key])) && strlen($req[$key]) > 0)
			{
				return $req[$key];
			}
		}
		elseif(isset(PXFRequest::$params[$key]))
		{
			return PXFRequest::$params[$key];
		}
	
		return false;
	}

	public static function reqGetOr404($key)
	{
		$value = PXFRequest::reqGet($key);	
		if(!$value)
			PXFRequest::redirect404();
		else
			return $value;
	}

	public static function reqGetOrDefault($key,$default)
	{
		$value = PXFRequest::reqGet($key);	
		return ($value) ? $value : $default;
	}

	public static function redirect404()
	{
		$smarty = '';
		PXFRequest::redirect(build_url(array('controller' => 'pages', 'item' => '404'),$smarty));
	}

	public static function redirect($location)
	{
		header(sprintf('Location: %s',$location));
		exit();
	}
}

function get_flashes($attrs,&$obj)
{
	$flashes = PXFInstance::$flashes;
	if(count($flashes))
	{
		foreach($flashes as $flash)
			print sprintf('<p class="%s"">%s</p>',$flash['type'],$flash['msg']);
	}
}
?>
